//
//  NJXTLoginHelper.m
//  jiaoxuetong
//
//  Created by zhaoliang on 15/12/8.
//  Copyright © 2015年 zhaoliang. All rights reserved.
//

#import "NJXTLoginHelper.h"
#import "MYY_User.h"
#import "UICKeyChainStore.h"

#define kCurrentUserToken @"currentUserToken"
#define kAllUsersToken @"allUsersToken"
#define kAllIsLogin @"AllIsLogin"
@interface NJXTLoginHelper()

@property(nonatomic, strong) UICKeyChainStore *keychain;
@property(nonatomic, copy) NSString *serviceName;

@end

@implementation NJXTLoginHelper

+ (instancetype)helper
{
    static NJXTLoginHelper *helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[NJXTLoginHelper alloc] init];
    });
    
    return helper;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.keychain = [UICKeyChainStore keyChainStoreWithService:[[NSBundle mainBundle] bundleIdentifier]];
    }
    return self;
}

- (MYY_User *)readUser:(NSString *)token
{
    if (token == nil || [token isEqualToString:@""]) {
        return nil;
    }
    NSData *data = [self.keychain dataForKey:kAllUsersToken];
    NSMutableArray *allUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    __block MYY_User *result = nil;
    [allUsers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MYY_User *user = (MYY_User *)obj;
        if ([user.token isEqualToString:token]) {
            result = user;
            *stop = YES;
        }
    }];
    return result;
}

- (MYY_User *)readCurrentUser
{
    NSData *data = [self.keychain dataForKey:kCurrentUserToken];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

- (void)saveUser:(MYY_User *)user
{
    if (user == nil) {
        return;
    }
    // 设置当前用户
    NSData *currentUserData = [NSKeyedArchiver archivedDataWithRootObject:user];
    [self.keychain setData:currentUserData forKey:kCurrentUserToken];
    NSData *data = [self.keychain dataForKey:kAllUsersToken];
    NSMutableArray *allUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSArray *filterResult = [allUsers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"token!=%@", user.token]];
    NSMutableArray *mFilterResult = [NSMutableArray arrayWithArray:filterResult];
    [mFilterResult insertObject:user atIndex:0];
    if (mFilterResult.count > 5) {
        [mFilterResult removeLastObject];
    }
    NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:mFilterResult];
    [self.keychain setData:newData forKey:kAllUsersToken];
}

- (void)updateUser:(MYY_User *)user
{
    if (user == nil) {
        return;
    }
    NSData *data = [self.keychain dataForKey:kAllUsersToken];
    NSMutableArray *allUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    __block int index = -1;
    [allUsers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MYY_User *iUser = (MYY_User *)obj;
        if ([iUser.token isEqualToString:user.token]) {
            index = (int)idx;
            *stop = YES;
        }
    }];
    if (index >= 0) {
        allUsers[index] = user;
    }
    NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:allUsers];
    [self.keychain setData:newData forKey:kAllUsersToken];
    // 更新当前用户信息
    NSData *currentUserData = [NSKeyedArchiver archivedDataWithRootObject:user];
    [self.keychain setData:currentUserData forKey:kCurrentUserToken];
}

- (void)removeUser:(NSString *)token
{
    if (token == nil || [token isEqualToString:@""]) {
        return;
    }
    
    // 如果删除的是当前登录用户
    MYY_User *currentUser = [self readCurrentUser];
    if ([currentUser.token isEqualToString:token]) {
        [self.keychain removeItemForKey:kCurrentUserToken];
    }
    
    NSData *data = [self.keychain dataForKey:kAllUsersToken];
    NSMutableArray *allUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    __block int index = -1;
    [allUsers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MYY_User *user = (MYY_User *)obj;
        if ([user.token isEqualToString:token]) {
            index = (int)idx;
            *stop = YES;
        }
    }];
    if (index >= 0) {
        [allUsers removeObjectAtIndex:index];
    }
    NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:allUsers];
    [self.keychain setData:newData forKey:kAllUsersToken];
}

- (NSArray *)listAllUsers
{
    NSData *data = [self.keychain dataForKey:kAllUsersToken];
    NSMutableArray *allUsers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return [allUsers copy];
}

- (void)clearAllUsers
{
    [self.keychain removeItemForKey:kCurrentUserToken];
    [self.keychain removeItemForKey:kAllUsersToken];
}

- (void)clearCache:(MYY_User *)user
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[[paths objectAtIndex:0] stringByAppendingString:@"/Caches/"] stringByAppendingString:user.token];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:filePath error:nil];
}

@end
